from django.shortcuts import render, HttpResponse
from App.models import *


# Create your views here.
def add_person(request):
    # 方式1
    #  p = PersonModel(name="张三", age=25)
    # try:
    #     p = PersonModel()
    #     p.name = "李四"
    #     p.age = 30
    #     p.save()  # 保存到数据库
    # except Exception as e:
    #     return HttpResponse("添加失败")
    # # return render(request, "index.html", {"msg": "添加成功"})
    # return HttpResponse("添加成功")

    # 方式2
    # try:
    #     PersonModel.objects.create(name="王五", age=28)
    # except Exception as e:
    #     return HttpResponse("添加失败")
    # # return render(request, "index.html", {"msg": "添加成功"})
    # return HttpResponse("添加成功")

    # 方式3
    try:
        ret = PersonModel.objects.get_or_create(name="王小五", age=58)
        print("res:", ret)  # 返回一个元组 (对象, 是否创建)
        # res: (<PersonModel: PersonModel object (3)>, False)
        # res: (<PersonModel: PersonModel object (3)>, True)
    except Exception as e:
        return HttpResponse("添加失败")
    # return render(request, "index.html", {"msg": "添加成功"})
    return HttpResponse("添加成功")


def del_person(request):
    # 先找到要删除的数据，然后删除
    try:
        # p = PersonModel.objects.first()
        # p.delete()  # 删除单个对象

        p = PersonModel.objects.filter(age__gt=15)
        p.delete()  # 批量删除
        # 删除单个对象
        # PersonModel.objects.get(name="王小五").delete()
        # 批量删除
        # PersonModel.objects.filter(age=58).delete()
    except Exception as e:
        return HttpResponse("删除失败")
    return HttpResponse("删除成功")


def update_person(request):
    try:
        # 更新单个对象
        p = PersonModel.objects.get(name="王小五")
        p.age = 30
        p.save()

        # 批量更新
        PersonModel.objects.filter(age__gt=58).update(age=40)
    except Exception as e:
        return HttpResponse("更新失败")
    return HttpResponse("更新成功")


def get_person(request):
    try:
        # 获取单个对象
        p = PersonModel.objects.get(name="王小五")
        print(p.name, p.age)

        # 获取所有对象
        persons = PersonModel.objects.all()
        for person in persons:
            print(person.name, person.age)

        # 获取符合条件的对象
        filtered_persons = PersonModel.objects.filter(age__gt=20)
        for person in filtered_persons:
            print(person.name, person.age)

        result = PersonModel.objects.aggregate(models.Max("age"), models.Min("age"))
        print("Max Age:", result["age__max"])
    except Exception as e:
        return HttpResponse("查询失败")
    return HttpResponse("查询成功")


def paginate(request):
    pass
    # 分页查询
    # page,per_page,切片[(page-1)*per_page: page*per_page]
